import axios from "axios";
import router from "../router/index.js"
import {Message} from 'element-ui';

axios.defaults.baseURL = "http://localhost:8089"

axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"

axios.interceptors.request.use(config => {
    //添加token
    config.headers.token = localStorage.getItem("token") || "";
    config.headers.userBh = localStorage.getItem("userBh") || "";
    config.headers.permission_ids = localStorage.getItem("permission_ids") || "";
    config.headers.dzJks = localStorage.getItem("dzJks") || "";

    //返回配置，不然拿不到
    return config;
})


axios.interceptors.response.use(res => {
    const result = res.data;
        if (result != null) {
            const code = result.code

            if (code == '402') {
                Message.error("会话已经失效，请重新登录！")
                router.push("/login")
                try {
                    throw new Error('会话已经失效，请重新登录！'); // 抛出自定义错误
                } catch (error) {
                    console.error('An error occurred:', error);
                }
                result.code = "400"
            }

            if (code == "401") {
                Message.error("权限不足，请联系管理员添加权限！")
                router.push("/home/firstPage")
                try {
                    throw new Error('权限不足，请联系管理员添加权限！'); // 抛出自定义错误
                } catch (error) {
                    console.error('An error occurred:', error);
                }
                result.code = "400"
            }
        }
        //返回配置，不然拿不到
        return result;
    },
    error => {
        // 响应错误处理
        console.log(error)
    })


//导出axios实例
export default axios;
